package de.poketradeshop.ui.controller;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

import de.poketradeshop.database.DatabaseService;
import de.poketradeshop.ui.model.Customer;
import de.poketradeshop.ui.model.CustomerSession;
import de.poketradeshop.ui.model.Login;
import de.poketradeshop.ui.model.Order;
import de.poketradeshop.ui.model.OrderContainer;

@Named
@RequestScoped
public class LoginController implements Serializable {

	@Inject
	Login login;

	@Inject
	private CustomerSession customerSession;

	@Inject
	DatabaseService databaseService;
	
	@Inject
	Customer customer;
	

	public LoginController() {

	}

	/**
	 * Checks if customer email exists and if the password matches for the email.
	 * @return String
	 */
	public String checkPassword() {
		//Set password-string from login
		String password = login.getPassword();
		//Set email-string from login
		String email = login.getEmail();

		//Check if email exists in database
		boolean exists = databaseService.emailExists(email);

		if (exists) {
			//If Email exists, check if password matches with the email in database
			boolean passwordMatches = databaseService.passwordMatches(email, password);
			if (passwordMatches) {
				//If password matches with the email 
				//Set Customer-Name
				String name = databaseService.getNameByEmail(email);
				//Set Customer-id 
				int customerId = databaseService.getCustomerIdByEmail(email);

				//Check if Admin
				if (email.equals("admin")) {
					//if Email is "admin" login as ADMIN
					customerSession.logIn(name, customerId, true);
				} else {
					//Else login as customer
					customerSession.logIn(name, customerId, false);
				}

				return "index?faces-redirect=true";
			} else {
				//Return error message if password not matches
				FacesContext.getCurrentInstance().addMessage("loginForm:password", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Fehler", "Bitte überprüfen Sie Ihre Email/Password!"));
				return "";
			}
		} else {
			//Return error message if email not exists
			FacesContext.getCurrentInstance().addMessage("loginForm:email", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Fehler", "Bitte überprüfen Sie Ihre Email/Password!"));
			return "";
		}
	}

	/**
	 * Checks out customer from session
	 * @return String
	 */
	public String checkoutCustomer() {

		customerSession.logOut();
		
		customer.setBankAccountNo(null);
		customer.setBankCode(null);
		customer.setBankDepositor(null);
		customer.setCity(null);
		customer.setCompany(null);
		customer.setEmail(null);
		customer.setFriendcode(null);
		customer.setName(null);
		customer.setPostcode(null);
		customer.setStreet(null);
		customer.setTelephone(null);
		
		return "index.xhtml?faces-redirect=true";

	}

}
